<?php

namespace App\Http\Controllers;

use App\Mail\Register;
use App\Models\Business;
use App\Models\Region;
use App\Models\StaticRegion;
use Gregwar\Captcha\CaptchaBuilder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;

class CommonController extends Controller
{
    /**
     * 图形验证码
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function captcha()
    {
        $builder = new CaptchaBuilder(4);
        $builder->setBackgroundColor(241, 242, 247)->build();

        // 把验证码的值存入缓存，设置有效期为 30 分钟
        $key = 'captcha:' . uniqid();
        Cache::put($key, $builder->getPhrase(), 1800);

        return response()->json([
            'key' => $key,
            'image' => 'data:image/png;base64,' . base64_encode($builder->get())
        ]);
    }

    public function sendEmailCode(Request $request)
    {
        $validator = Validator::make($request->all(),
            [
                'email' => 'required|email|unique:users'
            ]
        );
        if ($validator->fails()) {
            return response()->json([
                'message' => $validator->errors()->first(),
            ], 400);
        }

        $cache_key = 'register:verification:code:' . $request->email;
        if (Cache::get($cache_key)) {
            return response()->json([
                'message' => __('message.common.send_mail_code.repeat_send')
            ], 400);
        }

        $limit_cache_key = 'register:verification:limit:' . $request->email . ':' . date('Ymd');
        if (Cache::get($limit_cache_key) >= 5) {
            return response()->json([
                'message' => __('message.common.send_mail_code.limit_send')
            ], 400);
        }

        $code = Str::random(6);
        Mail::to($request->email)->send(new Register($code));
        Log::info('email：' . $request->email . '，code：' . $code);

        Cache::put($cache_key, $code, 300);
        if (Cache::has($limit_cache_key)) {
            Cache::increment($limit_cache_key);
        } else {
            Cache::put($limit_cache_key, 1, 1800);
        }

        return response()->json([
            'errcode' => 0,
            'message' => __('message.common.send_mail_code.success')
        ]);
    }

    /**
     * FAQ
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function faq()
    {
        $data = [
            'en' => [
                [
                    'title' => 'Do you support free testing?',
                    'content' => "In order to prevent IP abuse, ipxproxy's residential proxies currently do not provide any free testing services."
                ],
                [
                    'title' => 'What total protocols does your proxy support?',
                    'content' => "Supports HTTP(s) / SOCKS5 protocol. When performing proxy work, just set the requested protocol and proxy directly."
                ],
                [
                    'title' => 'Do IPXProxy Residential Proxies automatically rotate?',
                    'content' => "Absolutely. By default, IPXProxy Residential Proxies are designed to rotate. Instead of offering a single, unchanging IP like static proxies, our rotating residential proxies give you a wide range of IP addresses to access. This ensures that you’re assigned a fresh, random IP at specified or random intervals based on your session preferences."
                ],
                [
                    'title' => 'How many devices can be connected to one line?',
                    'content' => "IPXProxy does not limit concurrency, but the bandwidth of a line is limited, and connecting too many devices may cause network instability."
                ],
                [
                    'title' => 'What should I do if my recharge does not arrive?',
                    'content' => "After recharging, you generally need to wait for the system to check in real time, there is a certain time delay for the balance to arrive in the account, usually 1-10 minutes, please wait a moment and then refresh to check.If your order has not arrived in more than 10 minutes, you can contact the official customer service, provide payment records, customer service will be happy to help you check the reason."
                ],
                [
                    'title' => 'How is bandwidth and request usage calculated in billing?',
                    'content' => "In our billing model, the bandwidth usage is calculated as the sum of data transmitted to and from the target site, which includes request headers, request data, response headers, and response data. For request-based plans, we only charge for successful requests."
                ]
            ],
            'zh-cn' => [
                [
                    'title' => '可以使用线路翻墙吗？',
                    'content' => "不可用，IPXProxy的线路已经屏蔽所有境内的IP访问，使用线路前，您需要自备境外环境。"
                ],
                [
                    'title' => '你们支持免费测试吗？',
                    'content' => "为了防止IP滥用，IPXProxy的住宅代理目前不提供任何免费测试服务。"
                ],
                [
                    'title' => '一条线路可以连接多少设备？',
                    'content' => "IPXProxy不会对使用并发做限制，但一条线路的宽带是有限的，连接太多设备可能会造成网络不稳定。"
                ],
                [
                    'title' => '你们的代理总共支持哪些协议？',
                    'content' => "支持 HTTP(s) / SOCKS5 协议。执行代理工作时，只需设置所请求的协议并直接代理即可。"
                ],
                [
                    'title' => '充值后未到账怎么办？',
                    'content' => "充值后一般需要等待系统实时检查，余额到账存在一定的时间延迟，一般为1-10分钟，请您稍等片刻再刷新查看。如果您的订单超过10分钟仍未到账，可以联系官方客服，提供支付成功记录，客服将竭诚帮助您查看原因。"
                ],
                [
                    'title' => '能不能帮我搭建境外环境？',
                    'content' => "IPXProxy不协助任何客户进行海外环境的搭建。 并且已基于国家法律法规，屏蔽了所有国内IP直连。"
                ]
            ]
        ];

        return response()->json([
            'errcode' => 0,
            'data' => $data[App::getLocale()]
        ]);
    }

    public function region(Request $request)
    {
        $type = $request->input('type', 'country');
        $code = $request->input('code', '');
        $data = [];
        if ($type == 'country') {
            if (App::getLocale() == 'en') {
                $data = Region::select('country_code as value', 'country as label')->groupByRaw('country_code, country')->get();
                foreach ($data as $item) {
                    $item->label = $item->label . '-' . $item->value;
                }
            } else {
                $data = Region::select('country_code as value', 'country_alias as label')->groupByRaw('country_code, country_alias')->get();
                foreach ($data as $item) {
                    $item->label = $item->label . '-' . $item->value;
                }
            }
        }

        if ($type == 'region') {
            $data = Region::select('region as label', 'region_code as value')->where('country_code', $code)->groupByRaw('region, region_code')->get();
        }

        if ($type == 'city') {
            $data = Region::select('city as label', 'city_code as value')->where('region_code', $code)->get();
        }

        $data = [
            'data' => $data,
            'points' => config('point')
        ];
        return response()->json($data);
    }

    public function staticRegion(Request $request)
    {
        $pid = $request->input('pid', 0);

        if (App::getLocale() == 'en') {
            $field = ['name', 'code'];
        } else {
            $field = ['alias as name', 'code'];
        }
        $data = StaticRegion::select($field)->where('pid', $pid)->where('name', '!=', '')->where('alias', '!=', '')->get();
        $data = [
            'data' => $data,
        ];
        return response()->json($data);
    }

    public function business(Request $request)
    {
        $data = Business::pluck('name');
        $data = [
            'data' => $data,
        ];
        return response()->json($data);
    }

    //
}
